package main.request;

import java.io.IOException;
import java.net.ServerSocket;

import utils.Debug;
import utils.RandomPort;
import main.process.FtpRequest;

public class RequestPasv implements ProcessRequestInterface {

	private static class SingletonHolder
	{		
		/** Instance unique non préinitialisée */
		private final static RequestPasv instance = new RequestPasv();
	}
	
	public static RequestPasv getInstance()
	{
		return SingletonHolder.instance;
	}
	
	@Override
	public void processRequest(String[] request, FtpRequest ftp) throws IOException {
		
		Debug.debug(this.getClass().getName(), request, ftp.getDebug());
		
		if(!request[0].equals("PASV"))
		{
			next(request, ftp);
		}
		
		else {
		try {
			ftp.setPassiveServer(new ServerSocket(RandomPort.randInt(1025,23000)));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		/* on se place sur le serveur passif */
		ftp.setPort(ftp.getPassiveServer().getLocalPort());
		System.out.println("Mode passif on");
		System.out.println("Port = "+ftp.getPort());
		String ipServer[] = ftp.getClientSocket().getLocalAddress().getHostAddress().split("\\.");
		int port1 = ftp.getPort() / 256;
		int port2 = ftp.getPort() % 256;

		String rep = ipServer[0] + "," + ipServer[1] + "," + ipServer[2] + "," + ipServer[3] + "," + port1 + "," + port2;
		ftp.write("227 Entering passive mode " +rep+"\n");

		ftp.setPassiveTrue();
		}
		
	}

	@Override
	public void next(String[] request, FtpRequest ftp) throws IOException {
		RequestPwd.getInstance().processRequest(request, ftp);
		
	}

}
